//
//  SportDetailVC.swift
//  TimeBoat
//
//  Created by bo wang on 2022/8/31.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import UIKit
import MJRefresh

class SportDetailVC: AppBaseVC {
    
    var unit: SportTotalDataSportUnit!
    var start: Date!
    var granularity: DateGranularity!
    var imei: String?
    
    private var sportType: Int { unit.sportType }
    private var end: Date { start.endDate(with: granularity) }
    private var sportName: String? { unit.sportName }
    
    @IBOutlet var fakeNaviBar: UIView!
    @IBOutlet var fakeTitleLabel: UILabel!
    @IBOutlet var tableView: UITableView!
    @IBOutlet var startDateLabel: UILabel!
    @IBOutlet var endDateLabel: UILabel!
    
    private var list: [SportDetailDataUnit] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        view.layoutIfNeeded()
        fakeTitleLabel.text = unit.sportName
        tableView.register(R.nib.chartSportCell)
        tableView.enableRefresh(callback: self, header: true, footer: false)
        tableView.refreshHeader?.beginRefreshing()
        
        startDateLabel.text = ChartsDataUtil.dateFormatter2.string(from: start)
        endDateLabel.text = ChartsDataUtil.dateFormatter2.string(from: end)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        tableView.contentInset.top = fakeNaviBar.bounds.height
        tableView.contentInset.bottom = SAFE_AREA_BOTTOM
    }

    func reloadData() {
        API.getSportDetailData(start, end: end, type: sportType, imei: imei) { [weak self] result in
            self?.tableView.endRefreshing()
            guard result.suc else {
                HUD.showFail(msg: result.errDesc)
                return
            }
            
            self?.list = result.dataList ?? []
            self?.tableView.reloadData()
        }
    }
}

extension SportDetailVC: RefreshProtocol {
    func onRefreshing(_ component: MJRefreshComponent, isLoadMore: Bool) {
        reloadData()
    }
}

extension SportDetailVC: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueCell(R.reuseIdentifier, for: indexPath) as! ChartSportCell
    
        let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.chartSportCell, for: indexPath)
        cell!.update(data: unit, detail: list[indexPath.row])
        return cell!
    }
}
